import heapq

class PriorityQueue:

    def __init__(self):
        self._queue = []
        self._index = 0

    def push(self, item, priority):
        # 往列表里存放一个(-priority, self._index, item)组成的元组
        # 优先级以负数的形式存放，是因为队列heappop时，总是会弹出最小元素
        # 如果优先级相同，则会对比index
        # index以递增的形式存在，则先入队的index 的值就会小于后入队的值，在队列heappop时就会优先弹出
        heapq.heappush(self._queue,(-priority, self._index, item))
        self._index += 1

    def pop(self):
        q = heapq.heappop(self._queue)
        #取出元组的最后一个元素
        return q[-1]

class Item:
    
    def __init__(self, name):
        self.name = name
    
    def __repr__(self):
        return 'Item({!r})'.format(self.name)

q = PriorityQueue()
q.push(Item('foo'),1)
# q.push(Item('bar'),5)
# q.push(Item('spam'),4)
q.push(Item('grok'),1)

print(q.pop())
print(q.pop())
# print(q.pop())
# print(q.pop())

